'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  Form,
  Icon,
  Input,
  InputNumber,
  Modal,
  notification,
  Popconfirm,
  Select,
  Table,
  Upload
} from 'antd';

import {FormField, FormLayout, ModalFooter, ModalView} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import notify from "../../../components/NotificationExtra";
import UploadPic from "../../../components/UploadPic";
import ViewTitle from "../../../components/ViewTitle";
import ModalSelectSalesProds from "./ModalSelectSalesProds";
import styles from "../../index.less";
import ModalSelectProcureMaterials from "./ModalSelectProcureMaterials";

moment.locale('zh-cn');

@Form.create()
@connect(({
            tenant,
            global,
            vendor,
            dic, finance, dict, customer
          }) => ({...tenant, ...dic, ...vendor, ...global, ...finance, ...dict, ...customer}))
export default class _ModalCreateOrEditInvoiceReceiptRecord extends FormBase {
  constructor(props) {
    super(props);
    const {record} = this.props;
    this.state = {...record};

  }

  componentDidMount() {
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
  }


  renderFoot = () => {
    const {foot, value, callback, modalRef, record, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }

              // _.map(this.state, (item, key) => {
              //   values[key] = item;
              // });
              const {name, code, fileList,records} = this.state;
              values.recordId = record ? record.recordId : undefined;
              values.name = name;
              values.code = code;
              values.fileList = fileList;
              values.records = records;
              callback(values);
              modalRef.close();
            });

          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  columns = () => {
    return [
      {title: '订单编码', dataIndex: 'salesOrderCode', key: 'salesOrderCode'},
      {title: '商品名称', dataIndex: 'prodName', key: 'prodName'},
      {title: '商品编号', dataIndex: 'prodCode', key: 'prodCode'},
      {title: '商品单价', dataIndex: 'price', key: 'price'},
      {title: '开票商品数量', dataIndex: 'count', key: 'count',  editable: true,},
      {
        title: '商品金额', dataIndex: 'count', key: 'count', render: (value, record) => {
          const {price = 0, count = 0} = record;
          return <div>{price * count}</div>;
        }
      },
      {title: '销售公司', dataIndex: 'division', key: 'division'},
      {title: '客户', dataIndex: 'customer', key: 'customer'},

      {
        title: '创建时间', dataIndex: 'createdTs', key: 'createdTs', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'spLotId', key: 'spLotId', fixed: 'right', render: (value) => {
          return <div>
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                const {records} = this.state;
                const temp = [];
                _.map(records, item => {
                  if (item.spLotId !== value) {
                    temp.push(item);
                  }
                });
                this.state.records = temp;
                this.componentDidMount();
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>}
          </div>;
        }
      }
    ];
  };
  materialCols(){
    return[
      {title:'采购单编码', dataIndex: 'procureOrderCode', key: 'procureOrderCode'},
      {title:'物料名称', dataIndex: 'name', key: 'name'},
      {title:'物料编码', dataIndex: 'code', key: 'code'},
      {title:'物料形态', dataIndex: 'subcategory', key: 'subcategory'},
      {title:'物料规格', dataIndex: 'spec', key: 'spec'},
      {title:'物料类型', dataIndex: 'type', key: 'type'},
      {title:'物料编号', dataIndex: 'number', key: 'number'},
      {title:'单价', dataIndex: 'price', key: 'price'},
      {title:'数量', dataIndex: 'count', key: 'count'},
      {title:'用途', dataIndex: 'target', key: 'target'},
      {title:'供应商', dataIndex: 'vendor', key: 'vendor'},
      {title:'采购类型', dataIndex: 'materialType', key: 'materialType'},
      {title:'采购公司', dataIndex: 'division', key: 'division'},
      {title:'采购日期', dataIndex: 'createdTs', key: 'createdTs',fixed:'right',render: value => {return <div>{moment(value).format('YYYY-MM-DD')}</div>}},
    ]
  }
  render() {
    const {form, vendors = [], divisionDict = [], customers = [],type, entityType = '客户'} = this.props;
    let {
      fileList, name, amount, invoiceNumber, division, taxRate, records = []
    } = this.state;
    const divisionName = type === 'invoicing' ? '销售公司' : '采购公司';
    const tableTitle = type === 'invoicing' ? '开票商品列表' : '收票物料列表';
    const cols = type === 'invoicing' ?this.getTableCols() :this.materialCols();
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Form>
        {<FormLayout form={form} cols={2}>
          <FormField
            label={entityType}
            name={'name'}
            initialValue={name}
            required={true}
          >
            <AutoComplete style={{width: '100%'}}
                          dataSource={this.getCustomerOpt(entityType === '客户' ? customers : vendors)}
                          allowClear
                          onChange={value => {
                            if (!value) {
                              this.state['name'] = '';
                              this.state['code'] = '';
                            }
                          }}
                          onSelect={(value, option) => {
                            const {key, props} = option;
                            this.state['code'] = key;
                            this.state['name'] = value;
                          }}

            >
            </AutoComplete>
          </FormField>
          <FormField
            label={divisionName}
            name={'division'}
            initialValue={division}
            required={true}
          >
            <Select allowClear>{this.getDivision(divisionDict)}</Select>
          </FormField>
          <FormField
            label={'发票号'}
            name={'invoiceNumber'}
            initialValue={invoiceNumber}
            required={true}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>
          <FormField
            label={'开票金额'}
            name={'amount'}
            initialValue={amount}
            required={true}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>
          <FormField
            label={'税率'}
            name={'taxRate'}
            initialValue={taxRate}
            required={true}
          >
            <Select allowClear style={{width: '100%'}}>
              {this.getSelectOption(this.taxRateOption1)}
            </Select>
          </FormField>
        </FormLayout>
        }
        {<ViewTitle title={tableTitle} actions={<Button type={'primary'} onClick={() => {
          type === 'invoicing' ? ModalView.open(ModalSelectSalesProds, {
            title: "选择订单商品",
            width: '1180px'
          }, {
            type,
            callback: (_prods) => {
              const {records = []} = this.state;
              if (records.length === 0) {
                this.state.records = [];
              }
              this.state.records.push(..._prods);
              this.componentDidMount();
            }
          }):ModalView.open(ModalSelectProcureMaterials, {
            title: "选择采购物料",
            width: '1180px'
          }, {
            type,
            callback: (_prods) => {
              const {records = []} = this.state;
              if (records.length === 0) {
                this.state.records = [];
              }
              this.state.records.push(..._prods);
              this.componentDidMount();
            }
          })
        }}>选择</Button>}></ViewTitle>}

        <Table
          className={styles.antTable}
          rowClassName={() => 'editable-row'}
          components={components}
          bordered={true}
          columns={ columns}
          dataSource={records}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          //  scroll={{ x: 1300 }}
        ></Table>


        <UploadPic title={'上传发票'} fileList={fileList} callback={f => this.state.fileList = f.fileList}></UploadPic>
        {/*{*/}
        {/*  <div style={{marginLeft: '64px'}}>*/}
        {/*    <Upload*/}
        {/*      action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件*/}
        {/*      listType="picture-card"*/}
        {/*      fileList={fileList}*/}
        {/*      accept={".png,.jpg"}*/}
        {/*      onPreview={this.picHandlePreview}*/}
        {/*      onChange={this.picHandleChange}*/}
        {/*      onDownload={file => {*/}
        {/*        console.log('ondownlad', file);*/}
        {/*      }}*/}
        {/*      beforeUpload={(file, fileList) => {*/}
        {/*        const isLt2M = file.size / 1024 / 1024 < 2;*/}
        {/*        if (!isLt2M) {*/}
        {/*          notify({type: 'error', message: '文件过大！'});*/}
        {/*          return isLt2M;*/}
        {/*        }*/}
        {/*        return false;*/}
        {/*      }}*/}
        {/*    >*/}
        {/*      {<div>*/}
        {/*        <Icon type="plus"/>*/}
        {/*        <div className="ant-upload-text">上传图片</div>*/}
        {/*      </div>}*/}
        {/*    </Upload>*/}
        {/*    <Modal visible={previewVisible} footer={null} onCancel={() => {*/}
        {/*      this.setState({previewVisible: false});*/}
        {/*    }}>*/}
        {/*      <img alt="example" style={{width: '100%'}} src={previewImage}/>*/}
        {/*    </Modal>*/}
        {/*  </div>*/}
        {/*}*/}
        {this.renderFoot()}
      </Form>
    );
  }
}
